<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <el-alert title="添加商品信息" type="info" center show-icon></el-alert>
      <!-- 步骤条 -->
      <el-steps :active="activeText - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        :model="addGoodsForm"
        :rules="addGoodsFormRules"
        ref="addGoodsFormRef"
        label-position="top"
      >
        <!-- tab栏 -->
        <el-tabs
          :tab-position="'left'"
          v-model="activeText"
          :before-leave="beforeChange"
          @tab-click="changeTabs"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addGoodsForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addGoodsForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addGoodsForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <!-- 级联选择器 -->
              <el-cascader
                v-model="addGoodsForm.goods_cat"
                :options="cateList"
                :props="cateProps"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 先渲染表单的item项 -->
            <el-form-item
              :label="item.attr_name"
              v-for="(item, index) in manyTableData"
              :key="index"
            >
              <!-- 加入多选框组 -->
              <!-- 这里的attr_vals想要遍历必须要转换为数组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="cb" v-for="(cb, i) in item.attr_vals" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="(item, index) in onlyTableData"
              :key="index"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="imgUrl"
              :headers="headerObj"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :on-success="handelSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addGoodsForm.goods_introduce"></quill-editor>
            <el-button type="primary" class="btn" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览的对话框 -->
    <el-dialog title="图片预览" :visible.sync="previewDialog" width="50%">
      <img :src="imgPath" alt class="imgStyle" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data () {
    return {
      // 定义选择中的步骤
      activeText: '0',

      // 获取后台商品分类数据并绑定给级联选择器的数组
      cateList: [],

      // 表单数据验证接收的对象
      addGoodsForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 定义一个商品分类的数组
        goods_cat: [],
        // 图片上传成功的数组
        pics: [],
        goods_introduce: '',
        attrs: []
      },

      // 表单数据验证
      addGoodsFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],

        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ]
      },

      // 级联选择器的props配置对象
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },

      // 动态参数的数据列表
      manyTableData: [],

      // 静态数据列表
      onlyTableData: [],

      // 配置图片上传的基准路径
      imgUrl: 'http://127.0.0.1:8888/api/private/v1/upload',

      // 设置一个基准请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },

      // 图片预览对话框的显示和隐藏
      previewDialog: false,

      // 图片显示的基准路径
      imgPath: ''
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取后台数据商品分类的方法
    async getCateList () {
      const { data: res } = await this.$http.get('/categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
      console.log(res.data)
    },
    // 鼠标点击级联选择器触发的事件
    handleChange () {
      // 只允许三级图标出现在选择框级联选择器
      if (this.addGoodsForm.goods_cat.length !== 3) {
        this.addGoodsForm.goods_cat = []
      }
      // console.log(this.addGoodsForm.goods_cat)
    },

    // 切换标签之前发生的事件
    beforeChange (activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addGoodsForm.goods_cat.length !== 3) {
        this.$message.error('请输入商品参数')
        return false
      }
    },

    // 鼠标点击tab栏切换的事件 tab-click
    async changeTabs () {
      // console.log(this.activeText)
      // 先判断是不是为1 是1才能进行下一步操作
      if (this.activeText === '1') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'many' }
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        // 在这之前要把attr_vals中的字符串形式的数据转换为数组
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(',')
        })
        this.manyTableData = res.data
        // console.log(res.data)
      } else if (this.activeText === '2') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'only' }
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        // 在这之前要把attr_vals中的字符串形式的数据转换为数组
        this.onlyTableData = res.data
        // console.log(res.data)
      }
    },

    // 监听上传成功的事件
    handelSuccess (response) {
      console.log(response)
      // 现获取储存的临时路径
      const picInfo = { pic: response.data.tmp_path }
      // 再将保存的临时路径push到addGoodsForm中
      this.addGoodsForm.pics.push(picInfo)
      // console.log(this.addGoodsForm)
    },

    // 预览图片触发的事件on-preview
    handlePreview (file) {
      // console.log(file)
      this.imgPath = file.response.data.url
      this.previewDialog = true
    },

    // 点击删除触发的事件on-remove
    handleRemove (file) {
      // console.log(file)
      const filePath = file.response.data.tmp_path
      const i = this.addGoodsForm.pics.findIndex(x => x.pic === filePath)
      this.addGoodsForm.pics.splice(i, 1)
      console.log(this.addGoodsForm)
    },

    // 添加商品
    addGoods () {
      // 先进行预校验
      this.$refs.addGoodsFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请输入相应的表单项!')
        }

        // 然后对相应的数据进行处理，将goods_cat变成字符串
        const form = _.cloneDeep(this.addGoodsForm)
        form.goods_cat = form.goods_cat.join(',')
        // 处理动态参数
        this.manyTableData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(',')
          }
          this.addGoodsForm.attrs.push(newInfo)
        })

        // 处理静态参数
        this.onlyTableData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addGoodsForm.attrs.push(newInfo)
        })
        form.attrs = this.addGoodsForm.attrs
        // console.log(form)
        const { data: res } = await this.$http.post('/goods', form)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.$router.push('/goods')
      })
    }

    // 保存修改参数的数据并同步到后台
    // async saveArrts (row) {
    //   console.log(row)
    //   const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
    //     attr_name: row.attr_name,
    //     attr_sel: row.attr_sel,
    //     attr_vals: row.attr_vals.join(',')
    //   })
    //   if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
    //   this.$message.success(res.meta.msg)
    // }
  },
  computed: {
    // 分类id
    cateId () {
      if (this.addGoodsForm.goods_cat.length === 3) {
        return this.addGoodsForm.goods_cat[2]
      }
      return null
    }
  }
}
</script>

<style lang="less" scoped>
.imgStyle {
  width: 100%;
}
.btn {
  margin-top: 65px;
}
</style>
